<template>
   <el-tabs v-model="tabs" class="demo-tabs" @tab-click="handleClick"
      style="width: 98%;;background: #fff;padding: 20px;box-sizing: border-box;">
      <el-tab-pane label="表单设计" name="first">
        
        <div class="bth-report" v-if="!isCheck">
            <el-button @click="goback"  type="primary">返回</el-button>
            <el-button @click="savebg"  type="primary">保存</el-button>
            <el-button @click="submitForm(ruleFormRef)" v-if="users.userRole!='1'" type="primary">上报</el-button>
        </div>
        <div class="table-box">
            <div class="table-title">
                {{ infoMsg.title }}
            </div>
            <div class="msg-box">
                <div style="width: 30%">
                <div class="enact"><span class="enact-first">表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span><span>{{infoMsg.tableNo}}</span></div>
                <div class="enact"><span class="enact-first">制定机关:</span>陕西省商务厅<span></span></div>
                <div class="enact"><span class="enact-first">批准机关:</span>陕西省统计局<span></span></div>
                <div class="enact"><span class="enact-first">批准文号:</span>陕统函〔2022〕35号<span></span></div>
                <div class="enact"><span class="enact-first">有效期至:</span>2025年4月<span></span></div>
                <div class="enact"><span class="enact-first" style="line-height: 32px;">时&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间:</span><span>
                    <el-date-picker
                        :disabled="isCheck"
                        v-model="infoMsg.time"
                        placeholder="年-月-日"
                        style="width: 200px;"
                        format="YYYY-MM-DD"
                        type="date"
                        value-format="YYYY-MM-DD"
                        />
                </span></div>
                </div>
            </div>
            <div class="agencyName">综合机关名称：<el-input  style="width: 160px;" v-model="infoMsg.agencyName" :disabled="isCheck" placeholder="请输入机关名称" /></div>
      </div>
        <div class="demo">
            <div>
                注: 1.表中产品依据国家统计局制定的《统计用产品分类目录》
            </div>
            <div>
                2.表中所填产品不少于5种(填报营业收入前五位的5种产品的产量，不满5种的按实有产品数填报)
            </div>
        </div>
        <el-form label-position="right" :model="form" style="width: 100%;" ref="ruleFormRef"
        :rules="rules">
        <el-table 
            border 
            :data="form.tableData"
            v-loading="loading"
             style="width: 100%;" 
             :header-cell-style="{
                background: '#E7F2FF',
                color: 'black',
                height:'60px',
                borderBottom: '1px solid rgb(102, 102, 102)',
                }">
                <el-table-column  label="产品名称" >
                    <template #default="{row,$index}">
                        <el-form-item :prop="`tableData.${$index}.productName`" :rules="rules.productName">
                        <el-input type="text" style="width: 100%;" v-model="row.productName" :disabled="isCheck" placeholder="产品名称" />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column  label="所属行业小类代码">
                    <template #default="{row,$index}">
                        <el-form-item :prop="`tableData.${$index}.code`" :rules="rules.code">
                        <el-input type="number" style="width: 100%;" v-model="row.code" :disabled="isCheck" placeholder="所属行业小类代码" />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column  label="计量单位">
                    <template #default="{row,$index}">
                        <el-form-item :prop="`tableData.${$index}.unit`" :rules="rules.unit">
                        <el-input type="text" style="width: 100%;" v-model="row.unit" :disabled="isCheck" placeholder="计量单位" />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column  label="产量" >
                    <template #default="{row,$index}">
                        <el-form-item :prop="`tableData.${$index}.num`" :rules="rules.num">
                        <el-input type="number" style="width: 100%;" v-model="row.num" :disabled="isCheck" placeholder="产量" />
                        </el-form-item>
                    </template>
                </el-table-column>
        </el-table>
        <el-form label-position="right" :model="infoMsg" style="width: 100%;" ref="ruleFormRef"
        :rules="rules">
        <div class="inforMsg">
            <div class="infor-item">
                <el-form-item prop="leader" label="单位负责人：" >
                   <el-input style="width: 350px;" v-model="infoMsg.leader" :disabled="isCheck" placeholder="请输入单位负责人" />
                </el-form-item>
            </div>
            <div class="infor-item">
                <el-form-item prop="statistical" label="统计负责人：" >
                   <el-input style="width: 350px;" v-model="infoMsg.statistical" :disabled="isCheck" placeholder="请输入统计负责人" />
                </el-form-item>
            </div>
            <div class="infor-item">
                <el-form-item prop="preparer" label="填表人：" >
                   <el-input style="width: 350px;" v-model="infoMsg.preparer" :disabled="isCheck" placeholder="请输入填表人" />
                </el-form-item>
            </div>
            <div class="infor-item">
                <el-form-item prop="tel" label="联系电话：" >
                   <el-input style="width: 350px;" v-model="infoMsg.tel" :disabled="isCheck" placeholder="请输入联系电话" />
                </el-form-item>
            </div>
            <div class="infor-item">
                <el-form-item prop="phone" label="手机号码：" >
                   <el-input style="width: 350px;" v-model="infoMsg.phone" :disabled="isCheck" placeholder="请输入手机号码" />
                </el-form-item>
            </div>
            <div class="infor-item">
                <el-form-item prop="date" label="报出日期：" >
                    <el-date-picker
                        :disabled="isCheck"
                        v-model="infoMsg.date"
                        placeholder="报出日期"
                        style="width: 350px;"
                        format="YYYY-MM-DD"
                        type="date"
                        value-format="YYYY-MM-DD"
                        />
                </el-form-item>
            </div>
        </div>
      </el-form>
        <div class="addbox"  v-if="!isCheck">
            <div class="icon" @click="addRows()">
                <el-icon :size="25" color="#666666">
                <Plus />
             </el-icon>
            </div>
        </div>
       </el-form>
      </el-tab-pane>
      <el-tab-pane :label="users.userRole=='1'?'文件查看':'文件上传'" name="second">
        <upfiles  :id="id"/>
      </el-tab-pane>
    </el-tabs>
</template>
<script lang="ts" setup>
import {ref,onMounted,reactive} from 'vue'
import upfiles from '@/components/upfiles.vue';
import { useRoute, useRouter } from "vue-router";
import type { FormInstance ,TabsPaneContext} from 'element-plus'
import { ElMessage } from 'element-plus'
import { reportfindById, reportpublish, getLast, editReports} from "@/util/api";
import { useStore } from '@/store'
const ruleFormRef = ref<FormInstance>();
const store = useStore()
const router = useRouter()
const users = store.state.userInfo
const query = useRoute().query
const id:any = ref("")
const isCheck:any=ref(false)
const templateId:any = ref('')//报表类型
const tabs:any = ref('')//展示的tab
const dataCopy:any = ref({})//报表原始数据
const infoMsg:any = ref({})
const loading = ref(false)
const nowtableNo = ref('')
const form = ref({
    tableData: <any>[]
})
const rules = reactive({
    productName: [
      { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    code: [
      { required: true, message: '请输入所属行业小类代码', trigger: 'blur' },
    ],
    unit: [
      { required: true, message: '请输入计量单位', trigger: 'blur' },
    ],
    num: [
      { required: true, message: '请输入产量', trigger: 'blur' },
    ],
    leader: [
      { required: true, message: '请输入单位负责人', trigger: 'blur' },
    ],
    statistical: [
      { required: true, message: '请输入统计负责人', trigger: 'blur' },
    ],
    preparer: [
      { required: true, message: '请输入填表人', trigger: 'blur' },
    ],
    tel: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
    ],
    date: [
      { required: true, message: '请输入报出日期', trigger: 'change' },
    ],
  })
 //获取报表 
const getTable = async()=>{
     loading.value = true
     let res:any = await reportfindById(query.id)
     console.log(res)
     dataCopy.value = res.data
     let list = []
     if(res.data.list!=null&&res.data.list!='null'){
        list = JSON.parse(res.data.list)
        form.value.tableData = list
        console.log(list)
     }else{
        form.value.tableData=[
            {
                productName:"",
                code:"",
                unit:"",
                num:""
            }
        ]
     }
     if(res.data.info!=null&&res.data.info!='null'){
        infoMsg.value = JSON.parse(res.data.info) 
        infoMsg.value['tableNo'] = nowtableNo.value
     }
     infoMsg.value.title=res.data.name
     loading.value = false
}
//添加行
const addRows = ()=>{
    const circle = form.value.tableData[0]; //取出数组中第一个对象
      if (circle) {
        const newObj = {};
        for (let key in circle) { //把第一个对象的属性都赋值给新对象newObj  然后每个属性的值都设置为空；
          newObj[key] = '';
        }
        form.value.tableData.splice(form.value.tableData.length , 0, newObj);
      }
}
//返回
const goback = () => {
    router.push('/monthReport')
}
//保存报表
const  savebg= async() => {
    saveInfo()
     let res:any = await editReports(dataCopy.value)
     if(res.code=='200')ElMessage.success('已保存') 
}
const saveInfo=()=>{
    if(!infoMsg.value.time){
        infoMsg.value.time = getCurrentTime()
    }
    if(!infoMsg.value.agencyName||infoMsg.value.agencyName==null){
        infoMsg.value.agencyName = dataCopy.value.developArea
    }
    dataCopy.value.info = JSON.stringify(infoMsg.value)
    dataCopy.value.list = JSON.stringify(form.value.tableData)
}
//上报
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
    if (!valid) return ElMessage.error('请填写完整再上报')    
    if(dataCopy.value.filesQ==null)return ElMessage.error('请先左上角上传文件')
    saveInfo()
    editReports(dataCopy.value).then(async (saves:any)=>{
        if(saves.code!='200')return
        let res:any= await reportpublish(id.value)
        if(res.code=='200'){
            router.push('/monthReport')
        }  
    })
    
    })
  }
  const  repair=(i:any)=>{
    if (i >= 0 && i <= 9) {
        return "0" + i;
    } else {
        return i;
    }
}
  const  getCurrentTime=()=> {
    var date = new Date();//当前时间
    var year = date.getFullYear() //返回指定日期的年份
    var month = repair(date.getMonth() + 1);//月
    var day = repair(date.getDate());//日
    //当前时间 
    var curTime = year + "-" + month + "-" + day;
    return curTime;
}
 const returnRatio=(a:any,b:any)=>{
    let ratio:any = ''
     if(!a||!b)return ratio
     a = Number(a)
     b = Number(b)
     ratio = (Math.round(a/b * 10000) / 100.00)+'%'
     if(ratio=='Infinity%')return 'Infinity'
     if(ratio=='NaN%')return '100%'
     return ratio
 } 
 const handleClick = (tab: TabsPaneContext, event: Event) => {
    getTable()
}
onMounted(()=>{
    console.log(query.isCheck)
    templateId.value= query.radio1
    tabs.value = query.tabs
    id.value = query.id
    if(query.isCheck){
        isCheck.value=true
    }else{
        isCheck.value=false
    }
    nowtableNo.value = "经开区统3表"
    getTable()
})
</script>
<style scoped>
.demo-tabs{
    width: 100vw;
    padding-bottom: 60px;
}
.table-box{
    width: 100%;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    margin-top: 20px;
} 
.agencyName{
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid rgb(102, 102, 102);
    height: 60px;
}
.msg-box{
    display: flex;
    justify-content: right;
    border-bottom: 1px solid black;
    border-top: 1px solid rgb(102, 102, 102);
    padding: 30px 0;
}
.table-title{
    text-align: center;
    font-size: 24px;
    background-color: #FF0000;
    line-height: 50px;
    color: #ffffff;
    border-bottom: 1px solid rgb(102, 102, 102);
}
.bth-report{
    width: 100%;
    display: flex;
    justify-content: right;
}
.inforMsg{
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}
.infor-item{
    width: 33.3333%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    border-top: none;
    padding-top: 20px;
}
.demo{
    border: 1px solid rgb(102, 102, 102);
    border-top:none ;
    box-sizing: border-box;
    padding: 10px;
}
.demo div{
    margin: 10px 0;
}
.addbox{
    width: 100%;
}
.icon{
    width: 40px;
    height: 30px;
    text-align: center;
    line-height: 40px;
    border: 1px solid #666666;
    border-top: none;
    box-sizing: border-box;
    margin: 0 auto;
    cursor: pointer;
}
</style>